package com.ai.zuochengyun.phase01.class06;

public class GraphGenerator {

    /**
     * matrix 是一个n*3的数组
     * @param matrix
     * @return
     */
    public static Graph createGraph(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return null;
        }
        Graph graph = new Graph();
        for (int[] ele : matrix) {
            int weight = ele[0];
            int from = ele[1];
            int to = ele[2];

            // 构建起点和目的地节点，并加入到点集
            if (!graph.nodes.containsKey(from)) {
                graph.nodes.put(from, new Node(from));
            }
            if (!graph.nodes.containsKey(to)) {
                graph.nodes.put(to, new Node(to));
            }

            // 修改节点的入度和出度等信息
            Node fromNode = graph.nodes.get(from);
            Node toNode = graph.nodes.get(to);
            fromNode.nexts.add(toNode);
            fromNode.out++;
            toNode.in++;

            // 构建两个节点之间的边，加入到边集
            Edge edge = new Edge(weight, fromNode, toNode);
            graph.edges.add(edge);

            // fromNode拥有的边
            fromNode.edges.add(edge);
        }
        return graph;
    }
}
